package com.zz.ecommerce.fileupload;

import com.zz.ecommerce.common.GridRequest;
import com.zz.ecommerce.common.GridResult;
import com.zz.ecommerce.fileupload.attachmentlist.AttachmentListService;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/uploadfile")
public class UploadFileController {

    @Autowired
    private UploadFileDao uploadFileDao;
    @Autowired
    private UploadFileService uploadFileService;
    @Autowired
    private AttachmentListService attachmentListService;

    private final org.slf4j.Logger logger = LoggerFactory.getLogger(getClass());

    @RequestMapping(value = "queryAllByAttach", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public List<UploadFile> queryAllByAttach(String attachId) {
        List<UploadFile> listFile = uploadFileDao.queryAllByAttach(attachId);
        return listFile;
    }

    @RequestMapping(value = "qryAll", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public List<UploadFile> queryAllFiles() {
        List<UploadFile> listFile = uploadFileDao.queryAllFiles();
        return listFile;
    }

    @RequestMapping(value = "qryAllPage", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public GridResult qryAllPage(GridRequest qryFile, UploadFile loadFile) {
        long totalCnt = uploadFileDao.queryAllCount();
        List<UploadFile> listFiles = uploadFileDao.queryAllFiles();
        GridResult gridResult = new GridResult<UploadFile>(listFiles, qryFile, totalCnt);
        return gridResult;
    }

    @RequestMapping(value = "demoList", method = {RequestMethod.GET, RequestMethod.POST})
    public String demoList() {
        return "demo/index";
    }

    @RequestMapping(value = "qry/{fileId}", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public List<UploadFile> queryFile(@PathVariable(value = "fileId") String fileId) {
        List<UploadFile> listFile = new ArrayList<UploadFile>();
        if (StringUtils.isNumeric(fileId)) {
            listFile = uploadFileDao.queryFilesById(fileId);
        }
        return listFile;
    }

    @RequestMapping(value = "add", method = {RequestMethod.POST})
    @ResponseBody
    public UploadFile addFile(HttpServletRequest request) throws IOException {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile multipartFile = multipartRequest.getFile("Filedata");
        String qryList = request.getParameter("listId");

        String listId = "";
        UploadFile file = uploadFileService.saveFile(multipartFile);
        if (StringUtils.isNotEmpty(qryList)) {
            listId = qryList;
            attachmentListService.insertAttchList(attachmentListService.generateListAttach(qryList, file.getFileId()));
        } else {
            listId = attachmentListService.insertAttchList(attachmentListService.generateListAttach(file
                    .getFileId()));
        }
        String saveFile2Db = StringUtils.defaultIfEmpty(request.getParameter("saveFile2Db"), "false");
        // 是否需要将文件内容保存到UPLOAD_FILE表中
        if (Boolean.parseBoolean(saveFile2Db)) {
            InputStream is = multipartFile.getInputStream();
            byte[] bytes = FileCopyUtils.copyToByteArray(is);
            uploadFileDao.updateFile(file.getFileId(), bytes);
        }

        if (StringUtils.isNotEmpty(listId)) {
            file.setListId(listId);
        }

        return file;
    }

    @RequestMapping(value = "delete", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public String deleteFile(UploadFile loadFile) {
        if (StringUtils.isNotEmpty(loadFile.getListId())) {
            attachmentListService.deleteAttchListById(loadFile.getListId(), loadFile.getFileId());
        }
        return "success";
    }

    @RequestMapping(value = "download", method = {RequestMethod.GET, RequestMethod.POST})
    public void download(HttpServletResponse response, HttpSession session, String fileId) throws IOException {
        UploadFile ufile = attachmentListService.queryOneAttchmentById(Long.valueOf(fileId));
        String filePath = uploadFileService.getUploadFilePath(ufile.getTrueFileName());
        File file = new File(filePath);
        ServletContext servletContext = session.getServletContext();
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(ufile.getFileName(), "utf-8"));
        response.setContentLength((int) file.length());
        response.setContentType(servletContext.getMimeType(ufile.getFileName()));
        OutputStream out = response.getOutputStream();
        out.write(FileUtils.readFileToByteArray(file));
        out.flush();
    }

    @RequestMapping(value = "getFile", method = {RequestMethod.GET, RequestMethod.POST})
    public void getFile(HttpServletResponse response, String fileId) throws IOException {
        UploadFile ufile = attachmentListService.queryOneAttchmentById(Long.valueOf(fileId));
        String filePath = uploadFileService.getUploadFilePath(ufile.getTrueFileName());
        File file = new File(filePath);
        response.setContentType("image/jpeg");
        response.setContentLength((int) file.length());
        OutputStream out = response.getOutputStream();
        out.write(FileUtils.readFileToByteArray(file));
        out.flush();
    }

    @RequestMapping(value = "doTemplateUpload", method = {RequestMethod.GET, RequestMethod.POST})
    public String doTemplateUpload(@RequestParam("file") MultipartFile file, String pages, ModelMap modelMap,
                                   String className, String key, HttpSession session, String type) {
        try {
            String returnMsg = uploadFileService.doTemplateUpload(file, className, key, session, type);
            if (StringUtils.isEmpty(returnMsg)) {
                String successMsg = "文件导入成功!";
                modelMap.addAttribute("msg", successMsg);
            } else {
                String errorMsg = "文件导入失败，请务必核对文件后再上传！错误信息如下：</br>";
                errorMsg += returnMsg;
                modelMap.addAttribute("msg", errorMsg);
            }
        } catch (ClassNotFoundException e) {
            String errorMsg = "文件导入失败：系统解析出现异常!";
            modelMap.addAttribute("msg", errorMsg);
        }
        return pages;
    }
}
